import ffmpeg from 'fluent-ffmpeg';

import { readList } from '../common.js';

import ffprobe from 'ffprobe-static';

import EventEmitter from 'node:events';
import { basename } from 'node:path';

ffmpeg.setFfprobePath(ffprobe.path);

// let name;

export class VTS extends EventEmitter {
    #name;
    constructor() {
        super();
    }

    // 计算单个视频的时长
    static getVideoDuration(videoPath) {
        // console.log(videoPath);
        return new Promise((resolve, reject) => {
            ffmpeg.ffprobe(videoPath, (err, metadata) => {
                if (err) {
                    console.log(`无法获取视频 ${videoPath} 的时长: ${err.message},输出0`);
                    resolve(0);
                } else {
                    const duration = metadata.format.duration; // 视频时长（秒）
                    resolve(duration);
                }
            });
        });
    }

    async calculateTotalDuration(videoFiles) {
        let totalDuration = 0;
        const len = videoFiles.length;
        for (let i = 0; i < len; i++) {
            const ent = videoFiles[i];
            const duration = await VTS.getVideoDuration(ent);
            if (duration === 0) {
                // 获取第二个反斜杠后面的内容
                const lastSecondBackslashIndex = ent.lastIndexOf('\\', ent.lastIndexOf('\\') - 1);
                const dirEnt = ent.slice(lastSecondBackslashIndex + 1);
                return { type: 0, dirEnt };
            }
            this.emit('progress', { i: i + 1, len });
            totalDuration += duration;
        }
        return totalDuration;
    }

    async vtss(fileListPath, nameW) {
        this.name = nameW;
        const videoFiles = readList(fileListPath);
        const totalDuration = await this.calculateTotalDuration(videoFiles);
        return totalDuration;
    }
}
